﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ERPStore.Extensions
{
	public static class CartExtensions
	{
		public static decimal GetMinimalOrderAmount(this ERPStore.Models.OrderCart cart)
		{
			var amount = 0m;
			if (cart.DeliveryAddress == null)
			{
				amount = GlobalConfiguration.Configuration.Settings.GetDefaultMinimalOrderAmount();
			}
			else
			{
				var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.Single(i => i.CountryId == cart.DeliveryAddress.CountryId);
				amount = deliveryCountry.MinimalOrderAmount;
			}
			return amount;
		}


		public static ERPStore.Models.Price GetMinimalOrderPrice(this ERPStore.Models.OrderCart cart, Models.UserPrincipal principal)
		{
			var amount = 0m;
			if (cart.DeliveryAddress == null)
			{
				amount = GlobalConfiguration.Configuration.Settings.GetDefaultMinimalOrderAmount();
			}
			else
			{
				var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.Single(i => i.CountryId == cart.DeliveryAddress.CountryId);
				amount = deliveryCountry.MinimalOrderAmount;
			}
			var taxRate = cart.GetShippingTaxRate(principal) / 100d;
			return new ERPStore.Models.Price(amount, taxRate);
		}

		public static ERPStore.Models.Price FreeOfShippingPrice(this ERPStore.Models.OrderCart cart, Models.UserPrincipal principal)
		{
			var amount = 0m;
			if (cart.DeliveryAddress == null)
			{
				amount = GlobalConfiguration.Configuration.Settings.GetDefaultDeliveryCountry().MinimalFreeOfCarriageAmount;
			}
			else
			{
				var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.Single(i => i.CountryId == cart.DeliveryAddress.CountryId);
				amount = deliveryCountry.MinimalFreeOfCarriageAmount;
			}
			var taxRate = cart.GetShippingTaxRate(principal) / 100d;
			return new ERPStore.Models.Price(amount, taxRate);
		}

		public static double GetShippingTaxRate(this ERPStore.Models.OrderCart cart, Models.UserPrincipal principal)
		{
			if (principal.CurrentUser != null
				&& principal.CurrentUser.Corporate == null)
			{
				return GlobalConfiguration.Configuration.Settings.GetDefaultShippingTaxRate();
			}

			if (cart.DeliveryAddress == null)
			{
				return GlobalConfiguration.Configuration.Settings.GetDefaultShippingTaxRate();
			}

			var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.Single(i => i.CountryId == cart.DeliveryAddress.CountryId);
			return deliveryCountry.TaxRate;
		}

	}
}
